<template>
  <a-modal
    v-model:visible="config.visible"
    title="选择门店"
    @cancel="handleCancel"
    @before-ok="handleBeforeOk"
  >
    <a-table
      :columns="columns"
      :data="dataList"
      :row-selection="rowSelection"
      :pagination="false"
      row-key="id"
      @selection-change="selectChange"
    >
    </a-table>
  </a-modal>
</template>

<script setup lang="ts">
  import { reactive, ref } from 'vue';
  import type { TenantInfo } from '@/types/api/tenant';
  import { getSelfTenant } from '@/api/tenant';
  import { getTenantId, setTenantId } from '@/utils/tenant';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';

  const router = useRouter();
  const config = reactive({
    visible: false,
  });
  const rowSelection = reactive({
    type: 'radio',
    defaultSelectedRowKeys: [],
  });

  const selectSuccess = () => {
    const { redirect, ...othersQuery } = router.currentRoute.value.query;
    router.push({
      name: (redirect as string) || 'Workplace',
      query: {
        ...othersQuery,
      },
    });
  };

  const dataList = ref<TenantInfo[]>([]);

  const selectChange = (rowKeys: any) => {
    rowSelection.defaultSelectedRowKeys = rowKeys;
  };

  const handleBeforeOk = (done: any) => {
    if (rowSelection.defaultSelectedRowKeys.length === 0) {
      Message.error('请选择门店');
    }
    setTenantId(rowSelection.defaultSelectedRowKeys[0]);
    selectSuccess();
    done();
  };
  const handleCancel = () => {
    config.visible = false;
  };

  const open = async () => {
    config.visible = true;
    const resp = await getSelfTenant();
    const tenantId = getTenantId();
    if (tenantId && tenantId !== 'undefined') {
      rowSelection.defaultSelectedRowKeys = [tenantId];
    }
    dataList.value = resp.data;
    // 如果只有一条数据，直接跳转
    if (dataList.value.length === 1) {
      setTenantId(dataList.value[0].id);
      selectSuccess();
    }
  };

  const columns = [
    {
      title: '门店Id',
      dataIndex: 'id',
    },
    {
      title: '门店名称',
      dataIndex: 'name',
    },
  ];

  defineExpose({ open });
</script>
